<?php
require_once 'lib/controllerWithoutGetOrPost.php';
require_once 'views/StandardView.php';
require_once 'db/MemberDB.php';
require_once 'views/MemberView.php';
require_once 'models/MemberModel.php';
$standardView = new StandardView($html, $_GET, $db);
$memberDB = new MemberDB($db);
$view = new MemberView($html);
$model = new MemberModel($memberDB, $view);

$text = '';
$changePasswordMessage = '';
$action = $db->escape($_POST['action']);
if ($action === 'login') {
    $username = $db->escape($_POST['username']);
    $password = $db->escape($_POST['password']);
    $text .= $model->loginUser($username, $password);
} else if ($action === 'changepw') {
    $oldPass = $_POST['oldPassword'];
    $newPass = $_POST['newPassword'];
    $confirmPass = $_POST['confirmPassword'];
    $changeResult = $model->changePassword($_SESSION, $oldPass, $newPass, $confirmPass);
    $changePasswordMessage = $view->text($changeResult);
} else if ($action === 'logout') {
    $model->resetSession($_SESSION);
}
if (isset($_GET['auth'])) {
    $auth = '';
    if (empty($_GET['auth'])) {
        $userId = $memberDB->escape($_GET['userid']);
        $auth = $memberDB->getAuthCode($userId);
    }
    $querystring = $_SERVER['QUERY_STRING'].$auth;
    header('Location: http://amemorytree.co.nz/resetPassword.php?'.$querystring);
}
$action = $db->escape($_GET['action']);
if ($action === 'logout') {
    $model->resetSession($_SESSION);
}
$userId = intval($_SESSION['user']);
if (!empty($userId)) {
    if (!empty($_SESSION['return'])) {
        header('Location: http://'.$_SERVER['SERVER_NAME'].$_SESSION['return']);
        $_SESSION['return'] = '';
    } else {
        $showOptions = ($action === 'options');
        $text .= $model->memberPage($userId, $changePasswordMessage, $showOptions);
    }
} else {
    $userId = intval($_GET['userid']);
    $return = $db->escape($_GET['return']);
    $text .= $model->userLogin($userId, $return);
}
$content = $view->render($text);
echo $standardView->render($content);
?>
